package com.example.happiness.controller.admin;

import com.example.happiness.constant.JwtClaimsConstant;
import com.example.happiness.pojo.Admin;
import com.example.happiness.pojo.adminvo.AdminLoginVO;
import com.example.happiness.properties.JwtProperties;
import com.example.happiness.result.Result;
import com.example.happiness.service.admin.AdminService;
import com.example.happiness.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "管理员相关接口")
@Slf4j
@RestController
@RequestMapping("/admin/admin")
public class AdminController {

    @Autowired
    AdminService manageService;
    @Autowired
    JwtProperties jwtProperties;


    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<AdminLoginVO> userlogin(@RequestBody Admin admin){
        Admin adminvo = manageService.adminLogin(admin);
        String password = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        log.info("管理员登录，工号：{}，密码：{}",admin.getManageid(),password);
        if (adminvo == null) {
            return Result.error("没有相关管理员");
        }else if(!adminvo.getPassword().equals(password)){
            return Result.error("密码错误");
        }
        Map<String,Object> claims = new HashMap();
        claims.put(JwtClaimsConstant.USER_ID,adminvo.getManageid());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        System.out.println(jwtProperties.getUserSecretKey());
        AdminLoginVO adminLoginVO = AdminLoginVO.builder()
                .admin(adminvo)
                .token(token)
                .build();
        return Result.success(adminLoginVO);
    }
}
